package com.imooc.ad.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Map;
import java.util.function.Supplier;

@Slf4j
public class CommonUtils {

    /** 若key对应的value为空,会将第二个参数的返回值存入map并返回 k->value
     *  若key对应的value不为空,则直接返回 value 值
     * */
    public static <K,V> V getorCreate(K key, Map<K,V> map, Supplier<V> factory){
        return map.computeIfAbsent(key,k->factory.get());
    }

    public static String stringConcat(String... args){
        StringBuilder result = new StringBuilder();

        for (String arg : args) {
            result.append(arg);
            result.append("-");
        }
        result.deleteCharAt(result.length()-1);

        return result.toString();
    }

    public static Date parseStringDate(String dateString){
        try{

            DateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
            return DateUtils.addHours(dateFormat.parse(dateString),-8);

        }catch (Exception e){
            log.error("parseStringDate error: {}",dateString);
            return null;
        }

    }

}
